import time

import pandas as pd
from prompt2_youchu import prompt_text
from requst_glm import predict as p1
from requst_baidu import predict as p2
import re,json
import configparser
# 创建ConfigParser对象
config = configparser.ConfigParser()
# 读取配置文件
config.read('config.ini')
# 获取配置项的值
src_file = config.get('path', 'src_file')

def parse_json(text: str) -> list:
    """
    description:对大模型的结果进行解析
    Args:
    text:大模型返回的结果

    Returns:
        解析后的结果
    """
    if text is None:
        return ""
    pattern = r'```json(.*)```'
    match = re.search(pattern, text, re.DOTALL)
    try:
        if match:
            json_text = match.group(1).strip()
            json_list = eval(json_text)
            return json_list
        else:
            json_list = eval(text)
            return json_list
    except Exception as e:
        print(e)
        return []

def getresult(row):
    title = row['标题']
    content = row['正文']
    ocr = row['OCR识别内容']
    # result = row['result']
    if True:#result == '':
        # keywords = config.get('path', 'keywords')
        content = prompt_text.format(title=title, content=content,ocr = ocr)
        # result = p1(content)#chatglm
        # result = p2(content)#baidu
        result = p2(content)#baidu

    try:
        result_json = parse_json(result)
    except Exception as e:
        result_json = result
        print(result_json)
        print(e)
    return result_json

def para_json_yibao(text):
    tag,emotion,correlation,rate,reason = "","","","",""
    try:

        if text is None or len(text) == 0:
            return (tag,emotion,correlation,rate,reason)
        else:
            data = eval(text)
            # data = json_text['data']
            tag = data['tag']
            emotion = data['emotion']
            correlation = data['correlation']
            if 'reason' in data:
                reason = data['reason']
            if 'rate' in data:
                rate = data['rate']
                if rate != 'nan' and float(rate) > 10:
                    rate = float(rate)/100
            return (tag,emotion,correlation,rate,reason)
    except Exception as e:
        print(e)
        print(text)
        return (tag,emotion,correlation,rate,reason)

def para_json_youchu(text):
    correlation = ""
    try:

        if text is None or len(text) == 0:
            return correlation
        else:
            data = eval(text)
            # data = json_text['data']
            correlation = data['correlation']
            score = data['score']
            # grade = data['grade']
            # point = data['point']

            return correlation,score
    except Exception as e:
        print(e)
        print(text)
        return correlation


if __name__ == '__main__':
    src_file = '分组合计_王润一1.xlsx'
    df = pd.read_excel(src_file,dtype={'文章ID':str})
    #column = 'glm'
    df['OCR识别内容'].fillna('',inplace=True)
    # df[['tag','emotion','correlation','rate','reason']] = df['result'].apply(lambda x: pd.Series(para_json(x)))
    #df[['tag_glm_big','emotion_glm_big','correlation_glm_big','rate_glm']] = df['glm'].apply(lambda x: pd.Series(para_json(x)))
    start = time.time()
    df['result'] = df.apply(getresult, axis=1)
    execution_time = time.time() - start
    print(f"程序执行时间: {execution_time:.6f} 秒")

    df.to_excel('result.xlsx',index=False)
    df = pd.read_excel('result.xlsx',dtype={'文章ID':str})
    df['result'].fillna('', inplace=True)

    df[["correlation","score"]] = df['result'].apply(lambda x: pd.Series(para_json_youchu(x)))
    df.to_excel('result.xlsx', index=False)
    print('PyCharm')
    # title = "邮储广东活动专区集花卡赢大奖"
    # text = "本帖最后由 卡农超管 于 2024-3-6 00:21 编辑 广州邮储最低cs"
    # ocr = ""
    # content = prompt_text.format(title=title, content=text, ocr=ocr)
    # result = p1(content)
    # print(result)